import logging
import os
import sys
from collections import OrderedDict
from json import loads, dumps

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QCheckBox, QPushButton, QHBoxLayout, QTableWidget, \
    QHeaderView, QTableWidgetItem, QMessageBox

from check_json_exam_module import check_exam_module
from config import saved_modules_path
from dialog_windows import AddModule
from prepare_for_examen import PrepareForExamen


class HomeWidget(QWidget):
    def __init__(self, mainwindow):
        QWidget.__init__(self)

        self.mainwindow = mainwindow
        try:
            with open(saved_modules_path, 'r') as inp:
                self.saved_modules = OrderedDict(loads(inp.read()))
        except FileNotFoundError:
            logging.info('Файла с сохранёнными модулями не существует.')
            self.saved_modules = OrderedDict()
        self.initUI()

    def add_module_function(self):

        self.add_module_window = AddModule()
        if self.add_module_window.exec_():
            self.chosen_module_file = self.add_module_window.packets_combobox.currentText().strip()

            if not check_exam_module(self.chosen_module_file):
                return

            if self.chosen_module_file in self.saved_modules.keys():
                logging.info(f'Модуль {self.chosen_module_file} уже есть в списке')
                return

            self.mainwindow.prepare_for_examen_widget = PrepareForExamen(self.chosen_module_file, self.mainwindow)
            self.exams_table.setRowCount(self.exams_table.rowCount() + 1)
            row = self.exams_table.rowCount() - 1
            self.exams_table.setItem(row, 0, QTableWidgetItem(self.mainwindow.prepare_for_examen_widget.examen_date))
            self.exams_table.setItem(row, 1, QTableWidgetItem(
                self.mainwindow.prepare_for_examen_widget.examen_discipline))
            self.exams_table.setItem(row, 4, QTableWidgetItem(self.mainwindow.prepare_for_examen_widget.examen_module))
            self.exams_table.setItem(row, 5, QTableWidgetItem('Подготовка'))
            continue_button = QPushButton(self.exams_table)
            continue_button.setText('Продолжить')
            self.exams_table.setCellWidget(row, 6, continue_button)
            continue_button.clicked.connect(lambda: self.mainwindow.show_prepare_for_examen_widget(self.chosen_module_file))

            self.saved_modules[self.chosen_module_file] = \
                {
                    "date": self.mainwindow.prepare_for_examen_widget.examen_date,
                    "discipline": self.mainwindow.prepare_for_examen_widget.examen_discipline,
                    "module": self.mainwindow.prepare_for_examen_widget.examen_module
                }

            with open(saved_modules_path, 'w') as out:
                out.write(dumps(self.saved_modules, indent=4))

    def initUI(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.addWidget(QLabel('<h2>Модули проведения ГИА в ППЭ</h2>'))
        layout.addWidget(QLabel('Выберите модуль в списке или добавьте новый'))
        add_module_widget = QWidget()
        add_module_widget_layout = QHBoxLayout()
        add_module_widget.setLayout(add_module_widget_layout)
        self.show_past_exams_checkbox = QCheckBox('Показать прошедшие экзамены')
        add_module_widget_layout.addWidget(self.show_past_exams_checkbox)
        add_module_widget_layout.addStretch()
        add_module_button = QPushButton('Добавить модуль')
        add_module_button.clicked.connect(self.add_module_function)
        add_module_widget_layout.addWidget(add_module_button)
        layout.addWidget(add_module_widget)

        self.exams_table = QTableWidget()
        headers = ['Дата', 'Предмет', 'Аудитория', 'Резерв', 'Модуль', 'Текущий статус', '']
        self.exams_table.setColumnCount(len(headers))

        self.exams_table.setRowCount(len(self.saved_modules.keys()))
        continue_buttons = []
        for row, key in enumerate(self.saved_modules.keys()):
            self.exams_table.setItem(row, 0, QTableWidgetItem(self.saved_modules[key]["date"]))
            self.exams_table.setItem(row, 1, QTableWidgetItem(self.saved_modules[key]["discipline"]))
            self.exams_table.setItem(row, 4, QTableWidgetItem(self.saved_modules[key]["module"]))
            self.exams_table.setItem(row, 5, QTableWidgetItem("Подготовка"))
            continue_buttons.append(QPushButton(self.exams_table))
            continue_buttons[-1].setText('Продолжить')
            self.exams_table.setCellWidget(row, 6, continue_buttons[-1])
            continue_buttons[-1].released.connect(lambda key=key: self.mainwindow.show_prepare_for_examen_widget(key))

        self.exams_table.setHorizontalHeaderLabels(headers)
        self.exams_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.exams_table)

        self.setObjectName('home_widget')
